import {
    View, TextInput, TouchableOpacity, Text,
    ScrollView, Modal as ModalRN, Image, Switch,
} from 'react-native';
import React, { useEffect, useState, useRef } from 'react';
import {
    WingBlank, Modal, Button, WhiteSpace, Toast,
} from '@ant-design/react-native';
import PropTypes from 'prop-types';
import ImageViewer from 'react-native-image-zoom-viewer';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import { HeaderBackButton } from '@react-navigation/elements';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Recorder from '../Recorder';
import styles from './styles';
import {
    saveNote, noteDetail, editNote,
} from '../../comconfig/sqlfun';
import { debounce } from '../../utils/common';

const options = {
    mediaType: 'photo',
    cameraType: 'back',
    saveToPhotos: true,
    selectionLimit: 0,
};
const AddNote = ({ navigation, route }) => {
    const {
        title, id, bookid, getList, isEditing, noteid,
    } = route.params;
    const [imgUri, setImgUri] = useState([]);
    const [images, setImages] = useState([]);
    const [recordUri, setRecordUri] = useState('');
    const [show, setShow] = useState(false);
    const [titleVal, onChangeTitleVal] = useState('无标题的笔记');
    const [textVal, onChangeTextVal] = useState('');
    const [visible, setVisible] = useState(false);
    const [viewPage, setViewPage] = useState(0);
    const [isEnabled, setIsEnabled] = useState(false);
    const [detail, setDetail] = useState('');
    const cRef = useRef(null);
    const addImage = async (type) => {
        const addUri = [];
        const viewUri = [];
        if (type === 'camera') {
            const resFromCamera = await launchCamera(options);
            const { uri } = resFromCamera.assets[0];
            setImgUri([...imgUri, uri]);
            setImages([...images, { url: uri }]);
        }
        if (type === 'library') {
            const resFromLib = await launchImageLibrary(options);
            // const { uri } = resFromLib.assets[0];
            for (let i = 0; i < resFromLib.assets.length; i += 1) {
                const { uri } = resFromLib.assets[i];
                addUri.push(uri);
                viewUri.push({ url: uri });
            }
            setImgUri([...imgUri, ...addUri]);
            setImages([...images, ...viewUri]);
        }
    };
    const addNote = () => {
        if (textVal === ''
            || textVal.trim().length === 0
        ) {
            Modal.alert(
                <Text style={{ color: '#0F8DE9' }}>你的笔记没有内容</Text>,
                null,
                [
                    { text: 'OK' },
                ],
            );
            return;
        }
        saveNote(titleVal, textVal, imgUri, recordUri, parseInt(id, 10));
    };
    const edit = () => {
        if (textVal === ''
            || textVal.trim().length === 0
        ) {
            Modal.alert(
                <Text style={{ color: '#0F8DE9' }}>你的笔记没有内容</Text>,
                null,
                [
                    { text: 'OK' },
                ],
            );
            return;
        }
        editNote(titleVal, textVal, imgUri, recordUri, parseInt(noteid, 10), parseInt(bookid, 10));
    };
    const getDetail = async () => {
        try {
            const list = await noteDetail(parseInt(noteid, 10), parseInt(bookid, 10));
            setDetail(JSON.parse(list));
        } catch (error) {
            Toast.info('获取数据失败', 1, undefined, false);
        }
    };
    navigation.setOptions({
        headerRight: () => (
            <TouchableOpacity
                onPress={() => debounce(() => {
                    if (!isEditing) {
                        addNote();
                        getList();
                        navigation.goBack();
                    } else {
                        edit();
                        getList();
                        navigation.goBack();
                    }
                })}
            >
                <AntDesign
                    name="form"
                    size={26}
                    color="#017BFF"
                    style={{ marginRight: 5 }}
                />
            </TouchableOpacity>
        ),
        headerLeft: () => (
            <HeaderBackButton
                style={{ position: 'relative', left: -13 }}
                onPress={() => {
                    if (cRef.current) {
                        cRef.current.stopAudio();
                    }
                    navigation.goBack();
                }}
            />
        ),
    });
    const delIamge = (i) => {
        Modal.operation([
            {
                text: '删除',
                onPress: () => {
                    const copyImages = [...images];
                    copyImages.splice(i, 1);
                    const copyImgUri = [...imgUri];
                    copyImgUri.splice(i, 1);
                    setImgUri(copyImgUri);
                    setImages(copyImages);
                },
                style: { color: '#0F8DE9' },
            },
            {
                text: '取消',
                onPress: () => null,
                style: { color: '#0F8DE9' },
            },
        ]);
    };
    useEffect(() => {
        if (isEditing) {
            navigation.setOptions({
                title,
            });
            getDetail();
        }
    }, []);
    useEffect(() => {
        if (detail !== '') {
            onChangeTitleVal(detail.title);
            onChangeTextVal(detail.detail);
            if (detail.voiceurl !== '') {
                setIsEnabled(true);
                setRecordUri(detail.voiceurl);
            }
            if (detail.imguri !== null && detail.imguri !== '') {
                const imgArr = JSON.parse(detail.imguri);
                const preView = [];
                setImgUri(imgArr);
                for (let i = 0; i < imgArr.length; i += 1) {
                    preView.push({ url: imgArr[i] });
                }
                setImages(preView);
            }
        }
    }, [detail]);
    return (
        <View style={{ flex: 1 }}>
            <TouchableOpacity
                activeOpacity={1}
            >
                <ScrollView>
                    <WingBlank>
                        <TextInput
                            placeholder="笔记"
                            placeholderTextColor="#5d5d7e"
                            style={{
                                height: 60, borderColor: 'gray', borderWidth: 0, fontSize: 30,
                            }}
                            onChangeText={
                                text => onChangeTitleVal(text)
                            }
                            value={titleVal}
                        />
                        <TextInput
                            multiline
                            placeholder="添加笔记..."
                            placeholderTextColor="#5d5d7e"
                            style={styles.textInput}
                            maxLength={200}
                            onChangeText={text => onChangeTextVal(text)}
                            value={textVal}
                            returnKeyLabel="done"
                        />
                        {imgUri.length === 0 ? null : (
                            <View style={{
                                flexDirection: 'row',
                                flexWrap: 'wrap',
                                // justifyContent: 'space-around',
                            }}
                            >

                                {
                                    imgUri.map((uri, i) => (
                                        <TouchableOpacity
                                            key={uri}
                                            onPress={() => { setVisible(true); setViewPage(i); }}
                                            onLongPress={() => delIamge(i)}
                                        >
                                            <Image
                                                style={styles.image}
                                                // resizeMethod
                                                resizeMode="contain"
                                                source={{
                                                    uri,
                                                }}
                                                defaultSource={
                                                    require('../../assets/images/notfound.jpeg')
                                                }
                                            />
                                        </TouchableOpacity>
                                    ))
                                }
                            </View>
                        )}
                        <WhiteSpace />
                        <Button
                            type="primary"
                            onPress={() => { setShow(true); }}
                            // disabled={imgUri.length === 2}
                        >
                            添加图片
                        </Button>
                        <WhiteSpace />
                        <View
                            style={{ flexDirection: 'row' }}
                        >
                            <Text style={styles.recorder}>添加录音</Text>
                            <Switch
                                trackColor={{ false: '#5d5d7e', true: '#81b0ff' }}
                                thumbColor={isEnabled ? '#108EE9' : '#fff'}
                                onValueChange={() => setIsEnabled(previousState => !previousState)}
                                value={isEnabled}
                            />
                        </View>
                        {
                            isEnabled && (
                                <Recorder
                                    ref={cRef}
                                    recordUri={recordUri}
                                    setRecordUri={setRecordUri}
                                />
                            )
                        }
                        <WhiteSpace />
                    </WingBlank>
                    <Modal
                        popup
                        visible={show}
                        animationType="slide-up"
                        maskClosable
                        onClose={() => setShow(false)}
                    >
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => { addImage('camera'); setShow(false); }}
                        >
                            拍摄
                        </Button>
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => { addImage('library'); setShow(false); }}
                        >
                            从相册选择
                        </Button>
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => setShow(false)}
                        >
                            取消
                        </Button>
                    </Modal>
                    <ModalRN visible={visible}>
                        <ImageViewer imageUrls={images} index={viewPage} />
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => setVisible(false)}
                        >
                            取消
                        </Button>
                    </ModalRN>
                </ScrollView>
            </TouchableOpacity>
        </View>
    );
};
AddNote.defaultProps = {
    route: {},
};
AddNote.propTypes = {
    route: PropTypes.objectOf(PropTypes.any),

};
export default AddNote;
